﻿using HuiLian.Model.Models;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HuiLian.Data.DataAccess.Base
{
    public class EFContext : DbContext
    {
        public EFContext(string nameOrConnectionString = @"data source=.\sqlite\db.sqlite;foreign keys=true")
            : base(nameOrConnectionString)
        {

        }

        public EFContext(DbConnection connection, bool contextOwnsConnection)
            : base(connection, contextOwnsConnection)
        {

        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // 用户
            modelBuilder.Entity<User>().Property(e => e.Id).IsRequired();
            modelBuilder.Entity<User>().Property(e => e.Username).IsRequired();
            modelBuilder.Entity<User>().Property(e => e.Password).IsRequired();
            modelBuilder.Entity<User>().Property(e => e.Telphone);
            modelBuilder.Entity<User>().Property(e => e.Remainder);
            modelBuilder.Entity<User>().Property(e => e.ImagePath);
            modelBuilder.Entity<User>().Property(e => e.Available);

            EFContextDbInitializer initializer = new EFContextDbInitializer(modelBuilder);
            Database.SetInitializer(initializer);
        }

        private static EFContext context = null;
        /// <summary>
        /// 数据库上下文
        /// </summary>
        internal static EFContext Context
        {
            get
            {
                if (context == null)
                {
                    context = new EFContext();
                }
                return context;
            }
        }

        /// <summary>
        /// 用户
        /// </summary>
        public DbSet<User> Users { get; set; }
        /// <summary>
        /// 食品
        /// </summary>
        public DbSet<Food> Foods { get; set; }
        /// <summary>
        /// 订单
        /// </summary>
        public DbSet<Order> Orders { get; set; }
        /// <summary>
        /// 订单条目
        /// </summary>
        public DbSet<OrderItem> OrderItems { get; set; }
    }
}
